package com.wandian.cqcsk.mvvm.main;

import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;

import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.mylib.libcore.AppContext;
import com.mylib.libcore.config.CoinTypeEnum;
import com.mylib.libcore.config.RouterConfig;
import com.mylib.libcore.eventbus.ChangeMessage;
import com.mylib.libcore.mvvm.BaseMVVMActivity;
import com.mylib.libcore.utils.ActivityUtil;
import com.mylib.libcore.utils.JsonUtil;
import com.mylib.libcore.utils.TabKeyUtils;
import com.mylib.libcore.utils.ToastUtil;
import com.mylib.libcore.utils.UIUtils;
import com.wandian.cqcsk.R;
import com.wandian.cqcsk.adapter.home.MainBtnRecycleAdapter;
import com.wandian.cqcsk.databinding.ActivityMainBinding;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONException;

import java.util.ArrayList;
import java.util.List;

import static androidx.fragment.app.FragmentStatePagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT;
import static com.mylib.libcore.config.AppSPKeyConfig.APP_FUNCTION_TABS;
import static com.mylib.libcore.config.AppSPKeyConfig.FIRST_OPEN_PAGE_TEXT;
import static com.mylib.libcore.config.AppSPKeyConfig.FIRST_PAGE_NAME;
import static com.mylib.libcore.config.AppSPKeyConfig.HOME_TAB_JSON;


/**
 * @author cl
 * @date 2020-08-26
 * @description 首页
 **/
@Route(path = RouterConfig.ROUTER_MAIN)
public class MainActivity extends  BaseMVVMActivity<MainActivityViewModel>{
    private ActivityMainBinding dataBinding;
    private long mKeyTime=0;//按先home键的时间
    private MainBtnRecycleAdapter mainBtnRecycleAdapter;
    private List<String> btnTitleList = new ArrayList<>();
    private String firstOpenPage = FIRST_OPEN_PAGE_TEXT;
    //开放功能
    private String tab_opens ="";
    private String tableJson="";
    @Override
    public void init(Bundle savedInstanceState) {
        dataBinding = DataBindingUtil.setContentView(this, R.layout.activity_main);
        dataBinding.setLifecycleOwner(this);

        String firstPage = AppContext.getInstance().getAppPreferencesHelper().getKeyValue(FIRST_PAGE_NAME);
        if(!UIUtils.isEmpty(firstPage)){
            firstOpenPage = firstPage;
        }else {
            AppContext.getInstance().getAppPreferencesHelper().setKeyValue(FIRST_PAGE_NAME,FIRST_OPEN_PAGE_TEXT);
        }
        EventBus.getDefault().register(this);
        dataBinding.setViewModel(mViewModel);
        ActivityUtil.getInstance().toFullWindows(this);
        initDataView();
//        //更具时间更换背景
//        TimeUtils.customHomeBgByTimeRl(this,dataBinding.rlRootContent);
        //关闭所有其他activity
        ActivityUtil.getInstance().clearAllActivityWithout(MainActivity.class);

    }

    private void initDataView(){
        btnTitleList.clear();
        tableJson = AppContext.getInstance().getAppPreferenceForever().getSelectTabs();//设置保存
        tab_opens = AppContext.getInstance().getAppPreferenceForever().getMainTabs()+"";//开放
        if(UIUtils.isEmpty(tableJson)){//默认底部选项
            initTabTitle(tab_opens);
        }else {
            try {
                JSONArray jsonArray = new JSONArray(tableJson);
                if(!UIUtils.isEmpty(jsonArray) && jsonArray.length()>0){
                    for(int i=0;i<jsonArray.length();i++){
                        String key = jsonArray.getString(i);
                        if(TabKeyUtils.checkTabCanUse(key)){//没限制直接添加
                            btnTitleList.add(key);
                        } else{
                            if(tab_opens.contains(key))btnTitleList.add(key);
                        }
                    }
                    if(!tableJson.contains(FIRST_OPEN_PAGE_TEXT)) btnTitleList.add(FIRST_OPEN_PAGE_TEXT);
                }else {
                    initTabTitle(tab_opens);
                }
            } catch (JSONException e) {
                e.printStackTrace();
                initTabTitle(tab_opens);
            }


        }
        //设置viewPage
        dataBinding.vpContent.setOffscreenPageLimit(btnTitleList.size());
        dataBinding.vpContent.setAdapter(new HomeFragmentAdapter(getSupportFragmentManager(),BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT));
        //设置recycleBtn
        mainBtnRecycleAdapter = new MainBtnRecycleAdapter(R.layout.item_home_grid_btn_style,firstOpenPage);
        RecyclerView.LayoutManager layoutManager = new GridLayoutManager(this,btnTitleList.size());
        dataBinding.recyclerHomeBtn.setLayoutManager(layoutManager);
        dataBinding.recyclerHomeBtn.setAdapter(mainBtnRecycleAdapter);
        mainBtnRecycleAdapter.setNewData(btnTitleList);
        mainBtnRecycleAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
                mainBtnRecycleAdapter.notifySelectItemState(baseQuickAdapter.getData().get(i).toString());
                notifySelectBtnPage(baseQuickAdapter.getData().get(i).toString());
            }
        });
        notifySelectBtnPage(firstOpenPage);
    }


    private void initTabTitle(String tabs){
        if(tabs.contains("天气"))btnTitleList.add("天气");
        if(tabs.contains("游戏")){
            btnTitleList.add("资讯");
            btnTitleList.add("微文");
            btnTitleList.add("视频");
            btnTitleList.add("玩赚");
        }else {
            btnTitleList.add("生活");
            btnTitleList.add("智库");
        }

        ArrayList<String> titleList = new ArrayList<>();
        boolean haveMainTitle = false;
        for(String title : btnTitleList){
            if(title.equals(FIRST_OPEN_PAGE_TEXT)){
                haveMainTitle = true;
            }else {
                titleList.add(title);
            }
        }
        if(!haveMainTitle) btnTitleList.add(FIRST_OPEN_PAGE_TEXT);
        AppContext.getInstance().getAppPreferenceForever().setSelectTabs( JsonUtil.toJson(titleList));
    }

    //切换viewPage
    private void notifySelectBtnPage(String btnTitle){
        int selectPage = 0;
        for(int i=0;i<btnTitleList.size();i++){
            if(btnTitle.equals(btnTitleList.get(i))){
                selectPage = i;
                break;
            }
        }
        Log.d("notifySelectBtnPage",selectPage+"==="+btnTitleList.toString());
        switch (btnTitle){

            case "生活":
                UIUtils.setKeyEveryDayCoin(CoinTypeEnum.BK_COIN);
                break;
            case "智库":
                UIUtils.setKeyEveryDayCoin(CoinTypeEnum.ZS_COIN);
                break;
            case "微文":
                UIUtils.setKeyEveryDayCoin(CoinTypeEnum.WW_COIN);
                break;
            case "资讯":
                UIUtils.setKeyEveryDayCoin(CoinTypeEnum.NEWS_COIN);
                break;
            case "游戏":
                UIUtils.setKeyEveryDayCoin(CoinTypeEnum.GAME_COIN);
                break;
            case "玩赚":
                UIUtils.setKeyEveryDayCoin(CoinTypeEnum.GAME_COIN);
                break;
            case "小说":
                UIUtils.setKeyEveryDayCoin(CoinTypeEnum.NOVEL_COIN);
                break;
            case "天气":
                UIUtils.setKeyEveryDayCoin(CoinTypeEnum.WEATHER_COIN);
                EventBus.getDefault().post(new ChangeMessage("changeWeather"));
                break;
            case "我的":
                EventBus.getDefault().post(new ChangeMessage("changeMine"));
                break;
            case "视频":
                UIUtils.setKeyEveryDayCoin(CoinTypeEnum.VIDEO_COIN);
                EventBus.getDefault().post(new ChangeMessage("changeVideo"));
                break;
        }
        dataBinding.vpContent.setCurrentItem(selectPage, false);
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void eventBusMessage(ChangeMessage changeMessage) {
        try {
            if(!UIUtils.isEmpty(changeMessage) && !UIUtils.isEmpty(changeMessage.getIsChange())){
                if(changeMessage.getIsChange().equals("changeMain")){
                    Log.d("changeMain","changeMain"+changeMessage.getValue());
                    if(!UIUtils.isEmpty(changeMessage.getValue())){
                        notifySelectBtnPage(changeMessage.getValue());
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onBackPressed() {
        if(!moveTaskToBack(false)) {
            ActivityUtil.getInstance().clearAllActivity();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if ((System.currentTimeMillis() - mKeyTime) > 1500) {
                mKeyTime = System.currentTimeMillis();
                ToastUtil.show("再按一次退出登录");
                return false;
            }
            else {
                //全部退出
                System.exit(0);
                //收起不退出
//                Intent home = new Intent(Intent.ACTION_MAIN);
//                home.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//                home.addCategory(Intent.CATEGORY_HOME);
//                startActivity(home);
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onDestroy() {
        try {
            EventBus.getDefault().unregister(this);
        }catch (Exception e){}
        super.onDestroy();
    }

}
